package dao.Impl;

import dao.UserRepository;
import entity.User;
import utils.JDBCTools;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class UserRepositoryImpl implements UserRepository {
    /**
     * 根据用户名密码查询数据库中是否有该用户
     *
     * @param username 用户名
     * @param password 密码
     * @return User对象
     */
    @Override
    public User login(String username, String password) {
        Connection connection = JDBCTools.getConnection();
        String sql = "select * from servicemanagementsystem.user where username=? and password=?";
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        User user = null;
        try {
            ps = connection.prepareStatement(sql);
            ps.setString(1, username);
            ps.setString(2, password);
            resultSet = ps.executeQuery();
            while (resultSet.next()) {
                Integer id = resultSet.getInt(1);
                String usernameFound = resultSet.getString(2);
                String passwordFound = resultSet.getString(3);
                user = new User(id,usernameFound,passwordFound);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCTools.release(connection, ps, resultSet);
        }
        return user;
    }
}
